<?php

namespace app\api\controller;

use app\common\controller\Api;
use addons\epay\library\Service as EpayService;
use EasyWeChat\Foundation\Application as WXPAY_APP;
use EasyWeChat\Payment\Order as WXPAY_ORDER;
use addons\third\model\Third;
use think\Db;
use think\Config;

/**
 * 订单接口
 */
class Order extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
        // $this->user_id = 2;
        $this->model = new \app\common\model\Order;
    }  

    /**
     * 确认下单页
     * @ApiSummary  (获取默认收货地址以及已选的手机属性参数)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/order/sure_order)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="goods_id",type=int,required=true,description="上传手机id")
     * @ApiParams   (name="num",type=int,required=true,description="商品数量")
     * @ApiParams   (name="rent_date",type=int,required=false,description="租期时间选择")
     * @ApiParams   (name="total_price",type=int,required=false,description="总价格")
     * @ApiParams   (name="goods_spec_id",type=int,required=true,description="无论是单规格还是多规格该值是唯一的。，单规格还是多规格的goods_spec_id在spec里面")
     * @ApiReturnParams (name="unit_price", type="decimal", required=true, description="单价")
     * @ApiReturnParams (name="chose", type="string", required=true, description="已选的租期或者属性，没有就返回空值")
     * @ApiReturnParams (name="address", type="string", required=true, description="地址信息，没有就返回空值")
     * @ApiReturnParams (name="num", type="int", required=true, description="商品数量")
     */
    public function sure_order()
    {
        $params = input();
        $goods_id = input('goods_id');
        if(empty($goods_id))$this->error('请上传手机id:goods_id');
        if(empty(input('num')))$this->error('请上传商品数量');
        if(empty($this->user_id))$this->error('请重新登录');
        $goods_data = Db::name('litestore_goods')->where(['goods_id'=>$params['goods_id']])->find();
        if(empty($goods_data))$this->error('商品信息不存在');

        $spec_data = Db::name('litestore_goods_spec')->where('goods_spec_id',$params['goods_spec_id'])->where('goods_id',$goods_id)->find();
        if(empty($spec_data))$this->error('商品多规格信息不存在');

        $address = Db::name('address')->where(['user_id'=>$this->user_id,'isdefault'=>1])->find();
        $return['address'] = $address?$address:'';
        $return['goods_data']['chose']='';
        $return['goods_data']['num']=$params['num'];
        $return['goods_data']['goods_spec_id']=$params['goods_spec_id'];
        $return['goods_data']['goods_id']=$params['goods_id'];
        $return['goods_data']['rent_date']=$params['rent_date'];
        $return['goods_data']['spec_type']=$goods_data['spec_type'];

        // 单规格情况下
        if($goods_data['spec_type']=='10'){
            // 如果选择了租机
            if(!empty($params['rent_date'])){
                // 根据 goods_spec_id 找到 租期价格数据

                $return['goods_data']['chose'] = $params['rent_date']; 

                $return['goods_data']['unit_price'] = $spec_data['day_price'];

                $return['goods_data']['total_price'] = $params['total_price'];
            }else{
                //正常单规格买
                $return['goods_data']['unit_price'] = $spec_data['goods_price'];//单价
                $return['goods_data']['total_price'] = $spec_data['goods_price']*$params['num'];
            }
            // 单规格的照片
            $return['goods_data']['cover'] = $goods_data['cover'];

        }else{
            //多规格的情况下

            // 查询选择了的属性值
            $spec_sku_id_array = explode('_', $spec_data['spec_sku_id']);
            foreach ($spec_sku_id_array as $key => $value) {
                $return['goods_data']['chose'] .= Db::name('litestore_spec_value')->where(['id'=>$value])->value('spec_value').'+';
            }
            // 如果选择了租机
            if(!empty($params['rent_date'])){
                // 根据 goods_spec_id 找到 租期价格数据

                $return['goods_data']['chose'] .= $params['rent_date'].'+'; 

                $return['goods_data']['unit_price'] = $spec_data['day_price'];

                $return['goods_data']['total_price'] = $params['total_price'];
            }else{
                //正常多规格买
                $return['goods_data']['unit_price'] = $spec_data['goods_price'];//单价
                $return['goods_data']['total_price'] = $spec_data['goods_price']*$params['num'];
            }
            // 多规格的照片
            $return['goods_data']['cover'] = $spec_data['spec_image'];
            
        }
        $return['goods_data']['chose'] = rtrim($return['goods_data']['chose'],'+');

        $return['goods_data']['goods_name'] = $goods_data['goods_name'];

        $this->success('确认下单页',$return);

    }

    /**
     * 生成订单调起支付
     * @ApiSummary  (调起支付)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/order/create_order)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="goods_id",type=int,required=true,description="上传手机id")
     * @ApiParams   (name="num",type=int,required=true,description="商品数量")
     * @ApiParams   (name="rent_date",type=int,required=false,description="租期时间选择")
     * @ApiParams   (name="total_price",type=decimal,required=false,description="总价格")
     * @ApiParams   (name="front_id_img",type=string,required=false,description="租期时候传身份证正面")
     * @ApiParams   (name="back_id_img",type=string,required=false,description="租期时候传身份证反面")
     * @ApiParams   (name="student_img",type=string,required=false,description="学生证照片")
     * @ApiParams   (name="goods_spec_id",type=int,required=true,description="无论是单规格还是多规格该值是唯一的。，单规格或者多规格的goods_spec_id在spec里面。")
     * @ApiParams   (name="address_id",type=int,required=true,description="收货地址id")
     */
    public function create_order()
    {
        $params = input();
        $goods_id = input('goods_id');
        if(empty($goods_id))$this->error('请上传手机id:goods_id');
        if(empty(input('num')))$this->error('请上传商品数量');
        if(empty($params['address_id']))$this->error('收货地址为空');
        if(empty($this->user_id))$this->error('请重新登录');

        // halt($params);
        $order_detail = $this->model->order_add($this->user_id, $params);
        if($order_detail==2){
            $this->error('当前库存不足');
        }else if($order_detail==3){
            $this->error('产品信息为空');
        }
        else if($order_detail==4){
            $this->error('产品多规格数据丢失，请重新下单');
        }else{
            // 发起微信支付
            $this->init_wx_pay_for_wxapp();
         
            $third = Third::where(['user_id' => $this->user_id, 'platform' => 'wxapp'])->find();
        
            $payment = $this->wxapp->payment;
            // halt($payment);
            $attributes = [
                'trade_type'       => 'JSAPI',
                'body'             => '二手手机',
                'detail'           => '二手手机',
                'out_trade_no'     => $order_detail['order_no'],
                'openid'           => $third['openid'],
                'total_fee'        => $order_detail['total_price']*100,
                'notify_url'       => 'https://phone-vicky.bidou88.cn/api/order/callback_for_wxapp',
            ];

            $order_detail = new WXPAY_ORDER($attributes);
            // halt($order_detail);
            $result = $payment->prepare($order_detail);
            if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
                $prepayId = $result->prepay_id;
                $config = $payment->configForJSSDKPayment($prepayId); // 返回数组
                return $this->success('订单创建成功,预支付成功',$config);
            }
            return $this->error('微信支付调用失败',$result);
        }
    }

    /**
     * 订单删除
     * @param int $order_id 订单id
     */    
    public function order_delete(){
        $now_status= Db::name('order')->where('id',input('order_id'))->delete();

        if($now_status)$this->success('操作成功');
        $this->error('操作失败');
    }

    /**
     * 确认收货
     * @param int $order_id 订单id
     */    
    public function sure_get(){
        $now_status= $this->model::get(input('order_id'));

        if($now_status['order_status']=='40')$this->error('请勿重复确认收货');
        if($now_status['order_status']!=='30')$this->error('该订单还没发货');

        $res = $now_status->save(['order_status'=>40]);
        if($res)$this->success('确认收货成功');
        $this->error('确认收货失败');
    }

    private function init_wx_pay_for_wxapp(){
        $config = get_addon_config('epay');
        $options = [
            'debug'  => false,
            'log' => [
                'level' => 'debug',
                'file'  => LOG_PATH . '/tmp/easywechat.log',
            ],
            'app_id'   => $config['wechat']['miniapp_id'],// 小程序 APPID
            'secret'   => $config['wechat']['app_secret'],//小程序密钥
            'payment' => [
                'merchant_id'        =>  $config['wechat']['mch_id'],//小程序商户号
                'key'                =>  $config['wechat']['key'],//小程序支付密钥
                'notify_url'         =>  \think\Request::instance()->domain().'/api/order/callback_for_wxapp',
            ],

        ];
        $this->wxapp = new WXPAY_APP($options);
    }

     /**
     * 小程序支付回调
     * @ApiSummary  (小程序支付回调)
     * @ApiRoute    (/api/index/callback_for_wxapp)
     */
    public function callback_for_wxapp(){
        $this->init_wx_pay_for_wxapp();
        $response = $this->wxapp->payment->handleNotify(function($notify, $successful){

            if ($successful) {
                $notify_json = json_encode($notify);
                if ($notify['return_code'] === 'SUCCESS') {
                    if($notify["result_code"] === "SUCCESS"){

                        Db::name('order')->where('order_no',$notify->out_trade_no)->where('pay_status',10)->update([
                            'pay_status' => '20',
                            'order_status' => '20',
                            'pay_time' => time(),
                        ]);

                        $order_data = Db::name('order')->where(['order_no'=>$notify->out_trade_no])->find();
                       
                        $goods_data = Db::name('litestore_goods')->where(['goods_id'=>$order_data['goods_id']])->find();
                        // deduct_stock_type 库存计算方式:10=下单减库存,20=付款减库存
                        if($goods_data['deduct_stock_type']==20){
                            Db::name('litestore_goods_spec')->where('goods_spec_id',$order_data['goods_spec_id'])->setDec('deduct_stock_type',$order_data['num']);//减库存
                        }
                    }
                }
            }

            return true; // 返回处理完成
            
            
        });
        $response->send();
    }

  

}
